package city.spring.modules.reception.service.impl;

import city.spring.domain.enums.CardExpenseRecordType;
import city.spring.modules.bed.entity.BedEntity;
import city.spring.modules.bed.entity.RoomTypeEntity;
import city.spring.modules.bed.service.BedRoomService;
import city.spring.modules.bed.service.BedService;
import city.spring.modules.bed.service.RoomTypeService;
import city.spring.modules.cardinfo.entity.CardNumberEntity;
import city.spring.modules.cardinfo.repository.CardNumberRepository;
import city.spring.modules.cardinfo.service.CardExpenseRecordService;
import city.spring.modules.cardinfo.service.CardNumberService;
import city.spring.modules.checkinfee.entity.CheckinfeeEntity;
import city.spring.modules.checkinfee.service.CheckinfeeService;
import city.spring.modules.checkinfeeDetail.entity.CheckinfeeDetailEntity;
import city.spring.modules.checkinfeeDetail.service.CheckinfeeDetailService;
import city.spring.modules.consumptionItem.service.ConsumptionCategoryService;
import city.spring.modules.consumptionItem.service.ConsumptionItemsService;
import city.spring.modules.oldman.entity.*;
import city.spring.modules.oldman.service.*;
import city.spring.modules.oldman.vo.OldmanVO;
import city.spring.modules.reception.dto.CheckInDTO;
import city.spring.modules.reception.dto.SaveCheckInDTO;
import city.spring.modules.reception.dto.SavePayMoneyDTO;
import city.spring.modules.reception.entity.CheckInRecordEntity;
import city.spring.modules.reception.repository.CheckInRecordRepository;
import city.spring.modules.reception.service.CheckInRecordService;
import city.spring.modules.reception.service.CheckInService;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 入住登记
 *
 * @author HouKunLin
 * @date 2020/5/22 0022 11:50
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CheckInServiceImpl implements CheckInService {
    private final OldmanInfoService oldmanInfoService;
    private final OldmanFamilydependentService oldmanFamilydependentService;
    private final OldmanHealthInformationService oldmanHealthInformationService;
    private final BedService bedService;
    private final RoomTypeService roomTypeService;
    private final CheckInRecordService checkInRecordService;
    private final CardNumberService cardNumberService;
    private final CardExpenseRecordService cardExpenseRecordService;
    private final CardNumberRepository cardNumberRepository;
    private final OldmanAttendanceService oldmanAttendanceService;
    private final OldmanBedService oldmanBedService;
    private final ConsumptionCategoryService consumptionCategoryService;
    private final BedRoomService bedRoomService;
    private final ConsumptionItemsService consumptionItemsService;
    private final CheckinfeeDetailService checkinfeeDetailService;
    private final CheckInRecordRepository checkInRecordRepository;
    private final CheckinfeeService checkinfeeService;

    public CheckInServiceImpl(OldmanInfoService oldmanInfoService,
                              OldmanFamilydependentService oldmanFamilydependentService,
                              OldmanHealthInformationService oldmanHealthInformationService,
                              BedService bedService, RoomTypeService roomTypeService, CheckInRecordService checkInRecordService, CardNumberService cardNumberService, CardExpenseRecordService cardExpenseRecordService, CardNumberRepository cardNumberRepository, OldmanAttendanceService oldmanAttendanceService, OldmanBedService oldmanBedService, ConsumptionCategoryService consumptionCategoryService, BedRoomService bedRoomService, ConsumptionItemsService consumptionItemsService, CheckinfeeDetailService checkinfeeDetailService, CheckInRecordRepository checkInRecordRepository, CheckinfeeService checkinfeeService) {
        this.oldmanInfoService = oldmanInfoService;
        this.oldmanFamilydependentService = oldmanFamilydependentService;
        this.oldmanHealthInformationService = oldmanHealthInformationService;
        this.bedService = bedService;
        this.roomTypeService = roomTypeService;
        this.checkInRecordService = checkInRecordService;
        this.cardNumberService = cardNumberService;
        this.cardExpenseRecordService = cardExpenseRecordService;
        this.cardNumberRepository = cardNumberRepository;
        this.oldmanAttendanceService = oldmanAttendanceService;
        this.oldmanBedService = oldmanBedService;
        this.consumptionCategoryService = consumptionCategoryService;
        this.bedRoomService = bedRoomService;
        this.consumptionItemsService = consumptionItemsService;
        this.checkinfeeDetailService = checkinfeeDetailService;
        this.checkInRecordRepository = checkInRecordRepository;
        this.checkinfeeService = checkinfeeService;
    }

    /**
     * 处理入住登记信息
     *
     * @param dto 入住信息
     */
    @Override
    public void checkIn(CheckInDTO dto) {
        OldmanInfoEntity oldman = dto.getOldman();
        List<OldmanFamilydependentEntity> familys = dto.getFamilys();
        List<OldmanHealthInformationEntity> healths = dto.getHealths();
        BedEntity bed = dto.getBed();

        // 设置老人当前入住状态
        oldman.setStatus(dto.getCheckInRecord().getType());

        // 检查床位状态
        checkBedInfo(bed);
        // 检查老人信息是否存在
        checkOldManCertificateAlready(oldman);

        // 使用 saveOrUpdate 方便配合转入住功能，转入住时会带入老人ID的信息，因此需要使用该方法
        oldmanInfoService.updateOldmanInfo(oldman);

        // 一卡通设置  （新增一个老人，增加与老人对应的一条一卡通记录）
        // 先添加一卡通信息，在添加一卡通信息时,会员号:最大值+1，然后再把一卡通会员卡号赋值给老人信息表里面
        CardNumberEntity cardNumberEntity = new CardNumberEntity();
        cardNumberEntity.setPersonType("老人");
        cardNumberEntity.setBalance(BigDecimal.ZERO);
        cardNumberEntity.setDepositBalance(BigDecimal.ZERO);
        cardNumberEntity.setPerson(oldman.getId());
        // 会员号最大值+1
//        String maxnum = cardNumberRepository.getMaxnum().toString();
//        cardNumberEntity.setMemberCard(maxnum);
        cardNumberService.saveCardNumber(cardNumberEntity);

//        // 老人信息表会员卡号设置
//        oldman.setCardInfoId(cardNumberEntity.getId());
//        oldmanInfoService.updateOldmanInfo(oldman);

        // 修改床位信息
        updateBedInfo(oldman, bed);

        // 保存家属列表信息
        saveFamilys(oldman, familys);
        // 保存老人健康记录信息
        saveHealths(oldman, healths);
        // 保存入住记录
        saveCheckInRecord(dto);

        // 生成费用订单信息
        generateExpenseRecords(dto);
    }

    @Override
    public void saveCheckIn(SaveCheckInDTO dto) {
        OldmanVO oldman = dto.getOldman();
        CheckInRecordEntity checkInRecord = dto.getCheckInRecord();
        List<OldmanFamilydependentEntity> familys = dto.getFamilys();
        // 设置老人当前入住状态
        oldman.setStatus(dto.getCheckInRecord().getType());
        // TODO 保存或者更新老人信息
        oldmanInfoService.saveOrUpdate(oldman);

        // TODO 保存或者更新入住记录
        checkInRecord.setOldmanId(oldman.getId());
        checkInRecordService.saveOrUpdate(checkInRecord);

        // 一卡通设置  （新增一个老人，增加与老人对应的一条一卡通记录）
        // 先添加一卡通信息，在添加一卡通信息时,会员号:最大值+1，然后再把一卡通会员卡号赋值给老人信息表里面
        CardNumberEntity cardNumberEntity = new CardNumberEntity();
        cardNumberEntity.setPersonType("老人");
        cardNumberEntity.setBalance(BigDecimal.ZERO);
        cardNumberEntity.setDepositBalance(BigDecimal.ZERO);
        cardNumberEntity.setPerson(oldman.getId());
        cardNumberService.saveCardNumber(cardNumberEntity);

        if (familys == null || familys.isEmpty()) {
            // 老人家属列表为空，则删除数据库中与该老人关联的所有家属信息
            oldmanFamilydependentService.lambdaUpdate().eq(OldmanFamilydependentEntity::getOldmanId, oldman.getId()).remove();
            return;
        }
        // 设置老人家属信息对象与老人的ID关联
        familys.forEach(family -> family.setOldmanId(oldman.getId()));

        // TODO 差异对比家属信息，然后保存新的家属信息，或者删除家属信息
        List<OldmanFamilydependentEntity> list = oldmanFamilydependentService.lambdaQuery().eq(OldmanFamilydependentEntity::getOldmanId, oldman.getId()).list();
        // 数据库中已有的老人家属ID列表
        Set<String> dbIds = list.stream().map(OldmanFamilydependentEntity::getId).collect(Collectors.toSet());

        // 前端已有的老人家属ID列表
        Set<String> frontIds = familys.stream().filter(item -> StringUtils.isNotBlank(item.getId())).map(OldmanFamilydependentEntity::getId).collect(Collectors.toSet());

        // 取出前端被删掉的老人家属ID，然后从数据库删除，返回set（数据库中有的ID，但是前端没有的ID）
        Sets.SetView<String> removeIds = Sets.difference(dbIds, frontIds);
        if (!removeIds.isEmpty()) {
            oldmanFamilydependentService.removeByIds(removeIds);
        }

        // 保存新的老人家属信息（不存在ID的家属列表）
        List<OldmanFamilydependentEntity> saveFamilys = familys.stream().filter(item -> StringUtils.isBlank(item.getId())).collect(Collectors.toList());
        if (!saveFamilys.isEmpty()) {
            oldmanFamilydependentService.saveBatch(saveFamilys);
        }
        // 修改前端已有的老人家属信息
        List<OldmanFamilydependentEntity> updateFamilys = familys.stream().filter(item -> StringUtils.isNotBlank(item.getId())).collect(Collectors.toList());
        if (!updateFamilys.isEmpty()) {
            oldmanFamilydependentService.updateBatchById(updateFamilys);
        }
    }

    @Override
    public void changeBed(String oldmanId, String bedId) {
        OldmanInfoEntity oldman = oldmanInfoService.getById(oldmanId);
        if (oldman == null) {
            throw new RuntimeException("未找到老人信息");
        }
        Integer status = oldman.getStatus();
        if (status == null) {
            throw new RuntimeException("老人入住状态错误，请联系管理员核实");
        }
        if (!status.equals(1) && !status.equals(2)) {
            throw new RuntimeException("该老人未入住，请先安排老人入住");
        }

        BedEntity oldBed = bedService.lambdaQuery().eq(BedEntity::getOldmanId, oldmanId).one();
        BedEntity newBed = bedService.getById(bedId);
        if (newBed == null) {
            throw new RuntimeException("找不到床位信息");
        }
        if (newBed.getOldmanId() != null) {
            throw new RuntimeException("该床位已有人入住（或有人预约）");
        }
        newBed.setOldmanId(oldmanId);
        if (oldBed != null) {
            // 取消旧床位
            bedService.lambdaUpdate()
                    .set(true, BedEntity::getOldmanId, null)
                    .eq(BedEntity::getOldmanId, oldmanId)
                    .update();
        }
        // 更换新床位
        bedService.lambdaUpdate()
                .set(true, BedEntity::getOldmanId, oldmanId)
                .eq(BedEntity::getId, newBed.getId())
                .update();
    }

    @Override
    public void savePayMoney(SavePayMoneyDTO dto) throws ParseException {

//        Calendar c = Calendar.getInstance(); // 获取当前时间
//        int day = c.get(Calendar.DAY_OF_MONTH);    //获取当前天数
//        int first = c.getActualMinimum(Calendar.DAY_OF_MONTH);    //获取本月最小天数
//        int last = c.getActualMaximum(Calendar.DAY_OF_MONTH);    //获取本月最大天数
//        int overday = last - day +1; // 本月剩余天数
//        System.out.println(" 本月剩余天数 overday" + overday);

        // TODO 保存护理级别费用信息
        OldmanAttendanceEntity oldmanAttendance = dto.getOldmanAttendance();
        System.out.println("121212 oldmanAttendance" + oldmanAttendance);
//        ConsumptionCategoryEntity categoryEntity = consumptionCategoryService.getById(oldmanAttendance.getAttendanceId());
//        oldmanAttendance.setAttendanceFee(categoryEntity.getStandardPrice());
//        oldmanAttendance.setDiscountMoeny(categoryEntity.getDiscountMoeny());
//        oldmanAttendance.setAfterDiscount(categoryEntity.getAfterDiscount());

        Date date = oldmanAttendance.getEffectivetime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int fday = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH); // 护理级别生效时间 获取当前天数
        int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);    //护理级别生效时间 获取本月最大天数
        int overday = last - day + 1; // 本月剩余天数
        System.out.println(" 本月剩余天数 overday" + overday);

        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.DATE, fday);
        Calendar calendar11 = Calendar.getInstance();
        calendar11.set(Calendar.DATE, last);
        Date firstdayOfThemonth = calendar1.getTime(); // 本月第一天日期
        Date lastdayOfThemonth = calendar11.getTime(); // 本月最后一天日期

        System.out.println("本月第一天日期ijnkkkk" + firstdayOfThemonth);
        System.out.println("本月最后一天日期-0987654" + lastdayOfThemonth);


        // 获取护理等级标准费用
//        BigDecimal attendanceFee = oldmanAttendance.getAttendanceFee() == null ? BigDecimal.ZERO : oldmanAttendance.getAttendanceFee();
//        // 标准费用/本月最大天数 = 每天应收费用
//        BigDecimal attendanceDailyCost1 = attendanceFee.divide(BigDecimal.valueOf(last), 6, BigDecimal.ROUND_HALF_UP);
//        // 折后费用
//        BigDecimal afterDiscount = oldmanAttendance.getAfterDiscount() == null ? BigDecimal.ZERO : oldmanAttendance.getAfterDiscount();
//        // 标折后费用/本月最大天数 = 每天应收费用
//        BigDecimal attendanceDailyCost2 = afterDiscount.divide(BigDecimal.valueOf(last), 6, BigDecimal.ROUND_HALF_UP);
        /**  date1小于date2返回-1，date1大于date2返回1，相等返回0, date1小于等于date2 <1 ,date1大于等于date2 >-1
         *  计算是否优惠
         *  1.生效时间 9.1 <= 优惠开始时间 9.10，优惠结束时间 10.15 >= 月末最后一天 ：（优惠开始时间-生效时间）的标准费用 + （月末 — 优惠开始时间）的优惠费用
         *  2.生效时间 9.1 <= 优惠开始时间 9.10， 优惠结束时间 9.20 <= 月末最后一天 ： （优惠开始时间-生效时间）的标准费用 + （优惠结束-优惠开始）优惠费用 + （月末-优惠结束)标准收费
         *  3.生效时间 9.8 >= 优惠开始时间 9.1， 生效时间 9.8 >= 优惠结束时间 9.8  : 正常收费
         *  4. 生效时间 9.1 >= 优惠开始时间 9.1， 优惠结束时间 10.15 >= 月末最后一天: 本月剩余时间都优惠
         *  5. 生效时间 9.1 >= 优惠开始时间 9.1， 优惠结束时间 9。30 <= 月末最后一天 ： （优惠结束时间-生效时间）优惠费用 + （月末-优惠结束时间）标准收费
         */
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//        Date discountStartDate = sdf.parse(sdf.format(categoryEntity.getDiscountStartDate())); // 优惠开始时间
//        Date discountEndDate = sdf.parse(sdf.format(categoryEntity.getDiscountEndDate())); // 优惠开始时间
//        Date effectivetime = sdf.parse(sdf.format(oldmanAttendance.getEffectivetime())); // 生效时间
//        Calendar calcal = Calendar.getInstance();
//        calcal.setTime(discountStartDate);
//        long time1 = calcal.getTimeInMillis(); // 优惠开始时间
//        calcal.setTime(discountEndDate);
//        long time2 = calcal.getTimeInMillis(); // 优惠结束时间
//        calcal.setTime(effectivetime);
//        long time3 = calcal.getTimeInMillis();// 生效时间
//        calcal.setTime(lastdayOfThemonth);
//        long time4 = calcal.getTimeInMillis(); // 本月最后一天
//        System.out.println("time1:"+time1+",,time2:"+time2+",,time3:"+time3);
//
//        System.out.println("oldmanAttendance.getEffectivetime()"+oldmanAttendance.getEffectivetime());
//        System.out.println("categoryEntity.getDiscountStartDate()"+categoryEntity.getDiscountStartDate());
//        System.out.println("categoryEntity.getDiscountEndDate()"+categoryEntity.getDiscountEndDate());
//        System.out.println("lastdayOfThemonth"+lastdayOfThemonth);
//
//        // 1.生效时间 9.1 <= 优惠开始时间 9.1，优惠结束时间 12.1 >= 月末最后一天 ：（优惠开始时间-生效时间）的标准费用 + （月末 — 优惠开始时间）的优惠费用
//        if(oldmanAttendance.getEffectivetime().compareTo(categoryEntity.getDiscountStartDate()) <1
//                && (categoryEntity.getDiscountEndDate().compareTo(lastdayOfThemonth)) > -1){
//            // （优惠开始时间-生效时间）的标准费用 + （月末 — 优惠开始时间）的优惠费用
//            long noDiscountdays=categoryEntity.getDiscountStartDate().getTime() - oldmanAttendance.getEffectivetime().getTime(); // 没有优惠的天数
//            System.out.println("1 （优惠开始时间-生效时间）noDiscountdays "+noDiscountdays);
//            // 标准每天应收 * 没有优惠的天数
//            BigDecimal multiply = attendanceDailyCost1.multiply(BigDecimal.valueOf(noDiscountdays));
//            long isDiscountdays = lastdayOfThemonth.getTime() - categoryEntity.getDiscountStartDate().getTime(); // 本月优惠天数
//            System.out.println("1 （月末 — 优惠开始时间）isDiscountdays "+isDiscountdays);
//            // 折后每天应收 * 优惠的天数
//            BigDecimal multiply1 = attendanceDailyCost2.multiply(BigDecimal.valueOf(isDiscountdays));
//            // 本月应收
//            oldmanAttendance.setReceivableThisMonth(multiply.add(multiply1));
//            //2.生效时间 9.1 <= 优惠开始时间 9.10， 优惠结束时间 9.20 <= 月末最后一天 ： （优惠开始时间-生效时间）的标准费用 + （优惠结束-优惠开始）优惠费用 + （月末-优惠结束)标准收费
//        }else if (oldmanAttendance.getEffectivetime().compareTo(categoryEntity.getDiscountStartDate()) < 1
//                && (categoryEntity.getDiscountEndDate().compareTo(lastdayOfThemonth)) < 1){
//            // （优惠开始时间-生效时间）的标准费用 + （优惠结束-优惠开始）优惠费用 + （月末-优惠结束)标准收费
//            long noDiscountdays1 = (time1 - time3) / (1000 * 3600 * 24);
//            System.out.println("2 （优惠开始时间-生效时间）noDiscountdays1 "+noDiscountdays1);
//            long isDiscountdays = (time2 - time1) / (1000 * 3600 * 24);
//            System.out.println("2 （优惠结束-优惠开始） isDiscountdays "+isDiscountdays);
//            long noDiscountdays2 = (time4 - time2) / (1000 * 3600 * 24);
//            System.out.println("2 （月末-优惠结束) noDiscountdays2 "+noDiscountdays2);
//
//            BigDecimal multiply = (attendanceDailyCost1.add(BigDecimal.valueOf(noDiscountdays2))).multiply(BigDecimal.valueOf(noDiscountdays1));
//            BigDecimal multiply2 = attendanceDailyCost2.multiply(BigDecimal.valueOf(isDiscountdays));
//            // 本月应收
//            oldmanAttendance.setReceivableThisMonth(multiply.add(multiply2));
//           // 3.生效时间 9.8 >= 优惠开始时间 9.1， 生效时间 9.8 >= 优惠结束时间 9.8  : 正常收费
//        }else if (oldmanAttendance.getEffectivetime().compareTo(categoryEntity.getDiscountStartDate()) > -1
//                && (oldmanAttendance.getEffectivetime().compareTo(categoryEntity.getDiscountEndDate()) > -1)){
//            System.out.println("3.正常收费");
//            // 标准每天应收 * 本月剩余天数
//            BigDecimal multiply = attendanceDailyCost1.multiply(BigDecimal.valueOf(overday));
//            // 本月应收
//            oldmanAttendance.setReceivableThisMonth(multiply);
//            // 4. 生效时间 9.1 >= 优惠开始时间 9.1， 优惠结束时间 10.15 >= 月末最后一天: 本月剩余时间都优惠
//        }else if(oldmanAttendance.getEffectivetime().compareTo(categoryEntity.getDiscountStartDate()) > -1
//                && (categoryEntity.getDiscountEndDate().compareTo(lastdayOfThemonth)) > -1){
//            System.out.println("4.剩余天数都打折");
//            // 标准每天应收 * 本月剩余天数
//            BigDecimal multiply = attendanceDailyCost2.multiply(BigDecimal.valueOf(overday));
//            System.out.println("剩余天数都打折attendanceDailyCost2"+attendanceDailyCost2);
//            System.out.println("剩余天数都打折overday"+overday);
//            System.out.println("剩余天数都打折multiply:"+multiply);
//            // 本月应收
//            oldmanAttendance.setReceivableThisMonth(multiply);
//            // 5. 生效时间 9.1 >= 优惠开始时间 9.1， 优惠结束时间 9。30 <= 月末最后一天 ： （优惠结束时间-生效时间）优惠费用 + （月末-优惠结束时间）标准收费
//        }else if (oldmanAttendance.getEffectivetime().compareTo(categoryEntity.getDiscountStartDate()) > -1
//                && (categoryEntity.getDiscountEndDate().compareTo(lastdayOfThemonth)) < 1){
//           // （优惠结束时间-生效时间）优惠费用 + （月末-优惠结束时间）标准收费
//            long isDiscountdays = (time2 - time3) / (1000 * 3600 * 24);
//            System.out.println("5 （优惠结束时间-生效时间） isDiscountdays "+isDiscountdays);
//            // 折后每天应收 * 优惠的天数
//            BigDecimal multiply = attendanceDailyCost2.multiply(BigDecimal.valueOf(isDiscountdays));
//            long noDiscountdays = (time4 - time2) / (1000 * 3600 * 24);
//            System.out.println("5 （月末-优惠结束时间） noDiscountdays "+noDiscountdays);
//            // 标准每天应收 * 优惠的天数
//            BigDecimal multiply1 = attendanceDailyCost1.multiply(BigDecimal.valueOf(noDiscountdays));
//            // 本月应收
//            oldmanAttendance.setReceivableThisMonth(multiply.add(multiply1));
//        }else {
//            System.out.println("条件不符");
//        }


//        // 每天费用 * 本月剩余天数 = 本月应收费用
//        BigDecimal attendanceCostThisMonth = attendanceDailyCost.multiply(BigDecimal.valueOf(overday));
//        System.out.println(" 本月应收费用 attendanceCostThisMonth" + attendanceCostThisMonth);
        //设置本月应收费用
//        oldmanAttendance.setReceivableThisMonth(attendanceCostThisMonth);
        oldmanAttendanceService.saveOrUpdate(oldmanAttendance);

        // TODO 保存床位费用信息
        OldmanBedEntity oldmanBed = dto.getOldmanBed();
        System.out.println("oldmanBed:oldmanBed------" + oldmanBed);
        // 获取原来的床位信息
        OldmanBedEntity bedInfo = oldmanBedService.getBedInfoByoldmanId(oldmanBed.getOldmanId());
        System.out.println("bedInfo:bedInfo------" + bedInfo);
        // 原来的床位信息和现在的不相等 则将原来的床位设置为空
        if (bedInfo != null && !bedInfo.getBedId().equals(oldmanBed.getBedId())) {
            // 设置该床位为空
            BedEntity bedEntity = bedService.getById(bedInfo.getBedId());
            bedEntity.setOldmanId(null);
            bedService.lambdaUpdate()
                    .set(BedEntity::getOldmanId, bedEntity.getOldmanId())
                    .eq(BedEntity::getId, bedEntity.getId())
                    .update();
            oldmanBedService.removeById(bedInfo.getId());
        }

        // 根据床位id获取床位信息
        BedEntity bed = bedService.getById(oldmanBed.getBedId());

        //查找床位类型
        //1.根据床位信息的房间id查找房间信息
//        BedRoomEntity bedRoomEntity = bedRoomService.getById(bed.getBedRoomId());
        //2.根据房间信息的房间类型查找房间类型信息
//        RoomTypeEntity roomTypeEntity = roomTypeService.getById(bedRoomEntity.getRoomTypeId());
        //3.设置床位类型
//        oldmanBed.setBedType(roomTypeEntity.getId());
        // 床位费用
        //1.查找老人护理类型
//        String attendanceId = oldmanAttendance.getAttendanceId();
//        String bedId = oldmanBed.getBedId();
//        ConsumptionItemsEntity conItem = consumptionItemsService.getBedFee(attendanceId, bedId);
        // 床位标准费用
//        oldmanBed.setFee(conItem.getCost());
        // 优惠金额
//        oldmanBed.setDiscountMoeny(conItem.getDiscountMoeny());
        // 折后费用
//        oldmanBed.setAfterDiscount(conItem.getAfterDiscount());

        Date date1 = oldmanBed.getEffectivetime();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        int day1 = cal1.get(Calendar.DAY_OF_MONTH); // 床位生效时间 获取当前天数
        int last1 = cal1.getActualMaximum(Calendar.DAY_OF_MONTH);    //床位生效时间 获取本月最大天数
        int overday1 = last1 - day1 + 1; // 本月剩余天数
        System.out.println(" 本月剩余天数 overday1" + overday1);
//        cal.set(Calendar.DATE, last);
//        Date lastdayOfThemonth2 = cal.getTime(); // 本月最后一天日期
//        System.out.println("本月最后一天日期-lastdayOfThemonth2"+lastdayOfThemonth2);

        // 计算本月应收床位费用
        // 床位标准收费
//        BigDecimal fee = oldmanBed.getFee() == null ? BigDecimal.ZERO : oldmanBed.getFee();
//        // 标准费用/本月最大天数 = 每天应收费用
//        BigDecimal bedDailyCost1 = fee.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
//        // 折后费用
//        BigDecimal afterDiscountBed = oldmanBed.getAfterDiscount() == null ? BigDecimal.ZERO : oldmanBed.getAfterDiscount();
//        // 折后费用/本月最大天数 = 每天应收费用
//        BigDecimal bedDailyCost2 = afterDiscountBed.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
//        //优惠减免费用
//        BigDecimal discount = oldmanBed.getDiscounted() == null ? BigDecimal.ZERO : oldmanBed.getDiscounted();
//        // 优惠减免费用/本月最大天数 = 每天减免费用
//        BigDecimal bedDailyReduce = discount.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
//
//        BigDecimal bedFee = null;
        // TODO 床位价格计算
        Calendar calendar = Calendar.getInstance(); // 当前时间
        calendar.setTime(oldmanBed.getEffectivetime());  //放入Date类型数据
        int y = calendar.get(Calendar.YEAR);//获取年份
        int m = calendar.get(Calendar.MONTH) + 1;//获取月份
        int d = calendar.get(Calendar.DATE);//获取日

//        // TODO 1. 床位价格计算优惠 （标准收费（折后费用）-优惠减免费用）
//            BigDecimal reduceThisMonth = null; // 本月减免费用
//        // 优惠开始时间
//        if (oldmanBed.getDiscounted() != null) {
//            Calendar calendar2 = Calendar.getInstance(); // 当前时间
//            calendar2.setTime(oldmanBed.getDiscountStarttime());
//            int s = calendar2.get(Calendar.MONTH) + 1;
//
//            if (oldmanBed.getDiscountStarttime()!=null && oldmanBed.getEffectivetime()!=null) {
//                // 如果优惠开始时间在本月且优惠开始时间小于等于生效时间,且优惠结束时间大于月末最后一天 本月都减免
//                if (m == s && (oldmanBed.getDiscountStarttime().compareTo(oldmanBed.getEffectivetime()) == 0) && (oldmanBed.getDiscountEndtime().compareTo(lastdayOfThemonth2) == 1)) {
//                    // 本月优惠减免费用
//                    reduceThisMonth = bedDailyReduce.multiply(BigDecimal.valueOf(overday1));
//                    //如果优惠开始时间在本月且优惠开始时间大于生效时间 且优惠结束时间大于月末最后一天 (优惠开始时间-生效时间)不减(月末-优惠开始时间)减
//                } else if (m == s && (oldmanBed.getDiscountStarttime().compareTo(oldmanBed.getEffectivetime()) == 1) && (oldmanBed.getDiscountEndtime().compareTo(lastdayOfThemonth2) == 1)) {
//
//                    long l = lastdayOfThemonth2.getTime() - oldmanBed.getDiscountStarttime().getTime();
//                    reduceThisMonth = bedDailyReduce.multiply(BigDecimal.valueOf(l));
//                    //如果优惠开始时间在本月且优惠开始时间大于生效时间 且优惠结束时间小于月末最后一天 (优惠开始时间-生效时间)不减(优惠结束时间-优惠开始时间)减
//                } else if (m == s && (oldmanBed.getDiscountStarttime().compareTo(oldmanBed.getEffectivetime()) == 1) && (oldmanBed.getDiscountEndtime().compareTo(lastdayOfThemonth2) == -1)) {
//                    long isday = oldmanBed.getDiscountStarttime().getTime() - oldmanBed.getDiscountEndtime().getTime();
//                    reduceThisMonth = bedDailyReduce.multiply(BigDecimal.valueOf(isday));
//                    // //如果优惠开始时间在本月且优惠开始时间小于等于生效时间 且优惠结束时间小于月末最后一天 (优惠结束时间-生效时间)减(月末-优惠结束时间)不减
//                } else if (m == s && (oldmanBed.getDiscountStarttime().compareTo(oldmanBed.getEffectivetime()) == -1) && (oldmanBed.getDiscountEndtime().compareTo(oldmanBed.getEffectivetime()) == -1)) {
//                    long isddd = oldmanBed.getDiscountEndtime().getTime() - oldmanBed.getEffectivetime().getTime();
//                    reduceThisMonth = bedDailyReduce.multiply(BigDecimal.valueOf(isddd));
//                } else {
//                    reduceThisMonth = BigDecimal.ZERO;
//                }
//            }else {
//                reduceThisMonth = BigDecimal.ZERO;
//            }
//            System.out.println("reduceThisMonth"+reduceThisMonth);
//        }


        /**  date1小于date2返回-1，date1大于date2返回1，相等返回0
         *  计算是否优惠
         *  1.生效时间 9.8 < 优惠开始时间 9.15，优惠结束时间 10.15 >= 月末最后一天 ：（优惠开始时间-生效时间）的标准费用 + （月末 — 优惠开始时间）的优惠费用
         *  2.生效时间 9.8 < 优惠开始时间 9.15， 优惠结束时间 9.20 < 月末最后一天 ： （优惠开始时间-生效时间）的标准费用 + （优惠结束-优惠开始）优惠费用 + （月末-优惠结束)标准收费
         *  3.生效时间 9.8 > 优惠开始时间 9.1， 生效时间 9.8 >= 优惠结束时间 9.8  : 正常收费
         *  4. 生效时间 9.8 > 优惠开始时间 9.1， 优惠结束时间 10.15 >= 月末最后一天: 本月剩余时间都优惠
         *  5. 生效时间 9.8 > 优惠开始时间 9.1， 优惠结束时间 9。30 <= 月末最后一天 ： （优惠结束时间-生效时间）优惠费用 + （月末-优惠结束时间）标准收费
         */
//        SimpleDateFormat dedsdf=new SimpleDateFormat("yyyy-MM-dd");
//        Date beddiscountStartDate = dedsdf.parse(dedsdf.format(conItem.getDiscountStartDate())); // 优惠开始时间
//        Date beddiscountEndDate = dedsdf.parse(dedsdf.format(conItem.getDiscountEndDate())); // 优惠开始时间
//        Date bedeffectivetime = dedsdf.parse(dedsdf.format(oldmanBed.getEffectivetime())); // 生效时间
//        Calendar bedcalcal = Calendar.getInstance();
//        bedcalcal.setTime(discountStartDate);
//        long bedtime1 = bedcalcal.getTimeInMillis(); // 优惠开始时间
//        bedcalcal.setTime(discountEndDate);
//        long bedtime2 = bedcalcal.getTimeInMillis(); // 优惠结束时间
//        bedcalcal.setTime(effectivetime);
//        long bedtime3 = bedcalcal.getTimeInMillis();// 生效时间
//        bedcalcal.setTime(lastdayOfThemonth2);
//        long bedtime4 = bedcalcal.getTimeInMillis(); // 本月最后一天
//        System.out.println("bedtime1:"+bedtime1+",,bedtime2:"+bedtime2+",,bedtime3:"+bedtime3);
//
//        if(oldmanBed.getEffectivetime().compareTo(conItem.getDiscountStartDate())==-1 && (conItem.getDiscountEndDate().compareTo(lastdayOfThemonth2))==1){
//            // （优惠开始时间-生效时间）的标准费用 + （月末 — 优惠开始时间）的优惠费用
//            long noDiscountdays=(bedtime1-bedtime3)/(1000*3600*24); // 没有优惠的天数
//            System.out.println("1 （优惠开始时间-生效时间）noDiscountdays "+noDiscountdays);
//            // 标准每天应收 * 没有优惠的天数
//            BigDecimal multiply = bedDailyCost1.multiply(BigDecimal.valueOf(noDiscountdays));
//            long isDiscountdays = (bedtime4 - bedtime1) / (1000 * 3600 * 24); // 本月优惠天数
//            System.out.println("1 （月末 — 优惠开始时间）isDiscountdays "+isDiscountdays);
//            // 折后每天应收 * 优惠的天数
//            BigDecimal multiply1 = bedDailyCost2.multiply(BigDecimal.valueOf(isDiscountdays));
//            // 本月应收 = 费用合计-本月优惠减免
//            oldmanBed.setReceivableThisMonth(multiply.add(multiply1).subtract(reduceThisMonth));
//        }else if (oldmanBed.getEffectivetime().compareTo(conItem.getDiscountStartDate())==-1 && (conItem.getDiscountEndDate().compareTo(lastdayOfThemonth2))==-1){
//            // （优惠开始时间-生效时间）的标准费用 + （优惠结束-优惠开始）优惠费用 + （月末-优惠结束)标准收费
//            long noDiscountdays1 = (bedtime1 - bedtime3) / (1000 * 3600 * 24);
//            System.out.println("2 （优惠开始时间-生效时间）noDiscountdays1 "+noDiscountdays1);
//            long isDiscountdays = (bedtime2 - bedtime1) / (1000 * 3600 * 24);
//            System.out.println("2 （优惠结束-优惠开始） isDiscountdays "+isDiscountdays);
//            long noDiscountdays2 = (bedtime4 - bedtime2) / (1000 * 3600 * 24);
//            System.out.println("2 （月末-优惠结束) noDiscountdays2 "+noDiscountdays2);
//
//            BigDecimal multiply = (bedDailyCost1.add(BigDecimal.valueOf(noDiscountdays2))).multiply(BigDecimal.valueOf(noDiscountdays1));
//            BigDecimal multiply2 = bedDailyCost2.multiply(BigDecimal.valueOf(isDiscountdays));
//            // 本月应收= 费用合计-本月优惠减免
//            oldmanBed.setReceivableThisMonth(multiply.add(multiply2).subtract(reduceThisMonth));
//        }else if (oldmanBed.getEffectivetime().compareTo(conItem.getDiscountStartDate())==1 && (oldmanBed.getEffectivetime().compareTo(conItem.getDiscountEndDate())==1)){
//            System.out.println("3.正常收费");
//            // 标准每天应收 * 本月剩余天数
//            BigDecimal multiply = bedDailyCost1.multiply(BigDecimal.valueOf(overday));
//            // 本月应收= 费用合计-本月优惠减免
//            oldmanBed.setReceivableThisMonth(multiply.subtract(reduceThisMonth));
//        }else if(oldmanBed.getEffectivetime().compareTo(conItem.getDiscountStartDate())==1 && (conItem.getDiscountEndDate().compareTo(lastdayOfThemonth2))==1){
//            System.out.println("4.剩余天数都打折");
//            // 标准每天应收 * 本月剩余天数
//            BigDecimal multiply = bedDailyCost2.multiply(BigDecimal.valueOf(overday));
//            // 本月应收= 费用合计-本月优惠减免
//            oldmanBed.setReceivableThisMonth(multiply.subtract(reduceThisMonth));
//
//        }else if (oldmanBed.getEffectivetime().compareTo(conItem.getDiscountStartDate())==1 && (conItem.getDiscountEndDate().compareTo(lastdayOfThemonth2))==-1){
//            // （优惠结束时间-生效时间）优惠费用 + （月末-优惠结束时间）标准收费
//            long isDiscountdays = (bedtime2 - bedtime3) / (1000 * 3600 * 24);
//            System.out.println("5 （优惠结束时间-生效时间） isDiscountdays "+isDiscountdays);
//            // 折后每天应收 * 优惠的天数
//            BigDecimal multiply = bedDailyCost2.multiply(BigDecimal.valueOf(isDiscountdays));
//            long noDiscountdays = (bedtime4 - bedtime2) / (1000 * 3600 * 24);
//            System.out.println("5 （月末-优惠结束时间） noDiscountdays "+noDiscountdays);
//            // 标准每天应收 * 优惠的天数
//            BigDecimal multiply1 = bedDailyCost1.multiply(BigDecimal.valueOf(noDiscountdays));
//            // 本月应收= 费用合计-本月优惠减免
//            oldmanBed.setReceivableThisMonth(multiply.add(multiply1).subtract(reduceThisMonth));
//        }

        // 更新床位表 关联老人id
        bed.setOldmanId(oldmanBed.getOldmanId());
        bedService.lambdaUpdate()
                .set(BedEntity::getOldmanId, bed.getOldmanId())
                .eq(BedEntity::getId, bed.getId())
                .update();

        oldmanBedService.saveOrUpdate(oldmanBed);

        // TODO 保存入院收费记录

        // 查找是否有老人入院缴费记录
        CheckinfeeEntity checkinfee = checkinfeeService.getCheckinfeeWithCategory(oldmanAttendance.getOldmanId());
        System.out.println("checkinfee-------" + checkinfee);
        // 如果为空 则新增入院缴费记录 以及 缴费明细
        if (checkinfee == null) {
            // 获取年月日组成收费标记
            String mark = new SimpleDateFormat("yyyyMMdd").format(new Date());
//        String mark = String.valueOf(marky).concat(String.valueOf(m)).concat(String.valueOf(d));

            CheckinfeeEntity checkinfeeEntity = new CheckinfeeEntity();
            // 老人id
            checkinfeeEntity.setOldmanId(oldmanAttendance.getOldmanId());
            //老人证件信息
            OldmanInfoEntity oldman = oldmanInfoService.getById(oldmanAttendance.getOldmanId());
            System.out.println("oldman2345" + oldman);
            checkinfeeEntity.setCertificate(oldman.getCertificate());
            // 床位id
            checkinfeeEntity.setBedId(oldmanBed.getBedId());
            //护理级别
            checkinfeeEntity.setAttendanceId(oldmanAttendance.getAttendanceId());
            // 入住时间 获取最近的入住记录
            CheckInRecordEntity latestRecord = checkInRecordRepository.getLatestRecordByOldmanId(oldmanAttendance.getOldmanId());
            checkinfeeEntity.setCheckInTime(latestRecord.getCheckInTime());
            //入住类型
            checkinfeeEntity.setType(latestRecord.getType());
            //收费标记
            checkinfeeEntity.setMark(mark);
            // 缴费类别
            checkinfeeEntity.setCategory(1);
            // 缴费状态
            checkinfeeEntity.setStatus(0);
            // 缴存开始 = 护理级别生效时间
            checkinfeeEntity.setDateStart(oldmanAttendance.getEffectivetime());
            // 计算 缴存至 时间 如果追加月费为空 则缴存至时间为当前月末，否则是最大追加月费
            Calendar ca = Calendar.getInstance();

            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date time = ca.getTime();
            System.out.println("time====" + time);
            // 缴存至
            checkinfeeEntity.setDateTo(time);

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeEntity.getId()));
            checkinfeeService.saveOrUpdate(checkinfeeEntity);

            // TODO 保存入院收费明细：护理费用、床位费用、其他费用

            // TODO 保存追加月费用
//            List<CheckinfeeDetailEntity> monthlyfees = dto.getMonthlyfees();
//            monthlyfees.forEach(monthlyfee -> {
//                monthlyfee.setCheckinfeeId(checkinfeeEntity.getId());
//                monthlyfee.setMark(checkinfeeEntity.getMark());
//            });
//            checkinfeeDetailService.saveBatch(monthlyfees);

            checkinfeeService.lambdaUpdate()
                    .set(CheckinfeeEntity::getDateTo, checkinfeeEntity.getDateTo())
                    .eq(CheckinfeeEntity::getId, checkinfeeEntity.getId())
                    .update();

            // TODO 保存餐饮费用信息 6
            List<CheckinfeeDetailEntity> diningfee = dto.getDiningfee();
            for (CheckinfeeDetailEntity oldmanDiningfeeEntity : diningfee) {
                System.out.println("oldmanDiningfeeEntity:::" + oldmanDiningfeeEntity);
                // 收费id
                oldmanDiningfeeEntity.setCheckinfeeId(checkinfeeEntity.getId());
                // 老人id
                oldmanDiningfeeEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanDiningfeeEntity.setConsumptionItemsId(oldmanDiningfeeEntity.getConsumptionItemsId());
                // 收费标准
                oldmanDiningfeeEntity.setStandardPrice(oldmanDiningfeeEntity.getStandardPrice());
                // 费用类型
                oldmanDiningfeeEntity.setFeeType(6);
                // 收费标记
                oldmanDiningfeeEntity.setMark(checkinfeeEntity.getMark());
                // 缴费类型
                oldmanDiningfeeEntity.setType("入院缴费");
                oldmanDiningfeeEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanDiningfeeEntity.setDateTo(time);

                // 计算餐饮费
                BigDecimal fee1 = oldmanDiningfeeEntity.getStandardPrice() == null ? BigDecimal.ZERO : oldmanDiningfeeEntity.getStandardPrice();
                // 餐饮费每日费用
                BigDecimal DailyCost = fee1.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
                // 每天费用 * 本月剩余天数 = 本月应收费用
                BigDecimal costThisMonth = DailyCost.multiply(BigDecimal.valueOf(overday1));
                oldmanDiningfeeEntity.setReceivableThisMonth(costThisMonth);
                System.out.println("餐饮费" + oldmanDiningfeeEntity.getReceivableThisMonth());
            }
            checkinfeeDetailService.saveOrUpdateBatch(diningfee);

            // TODO 保存水电费用信息 7
            List<CheckinfeeDetailEntity> utilitybill = dto.getUtilitybill();
            for (CheckinfeeDetailEntity oldmanUtilitybillEntity : utilitybill) {
                // 收费id
                oldmanUtilitybillEntity.setCheckinfeeId(checkinfeeEntity.getId());
                // 老人id
                oldmanUtilitybillEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanUtilitybillEntity.setConsumptionItemsId(oldmanUtilitybillEntity.getConsumptionItemsId());
                // 收费标准
                oldmanUtilitybillEntity.setStandardPrice(oldmanUtilitybillEntity.getStandardPrice());
                // 费用类型
                oldmanUtilitybillEntity.setFeeType(7);
                // 收费标记
                oldmanUtilitybillEntity.setMark(checkinfeeEntity.getMark());
                // 缴费类型
                oldmanUtilitybillEntity.setType("入院缴费");
                oldmanUtilitybillEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanUtilitybillEntity.setDateTo(time);

                // 计算水电费
                BigDecimal fee1 = oldmanUtilitybillEntity.getStandardPrice() == null ? BigDecimal.ZERO : oldmanUtilitybillEntity.getStandardPrice();
                // 水电费每日费用
                BigDecimal DailyCost = fee1.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
                System.out.println("水电费 DailyCost" + DailyCost);
                // 每天费用 * 本月剩余天数 = 本月应收费用
                BigDecimal costThisMonth = DailyCost.multiply(BigDecimal.valueOf(overday1));

                oldmanUtilitybillEntity.setReceivableThisMonth(costThisMonth);
                System.out.println("水电费" + oldmanUtilitybillEntity.getReceivableThisMonth());
            }
            checkinfeeDetailService.saveOrUpdateBatch(utilitybill);

            // TODO 保存押金信息 4
            List<CheckinfeeDetailEntity> deposit = dto.getDeposit();
//        OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(oldmanAttendance.getOldmanId());
            for (CheckinfeeDetailEntity oldmanDepositEntity : deposit) {
//            oldmanDepositEntity.setCertificate(oldmanInfoEntity.getCertificate());
//            oldmanDepositEntity.setStatus(oldmanInfoEntity.getStatus());
                // 收费id
                oldmanDepositEntity.setCheckinfeeId(checkinfeeEntity.getId());
                // 老人id
                oldmanDepositEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanDepositEntity.setConsumptionItemsId(oldmanDepositEntity.getConsumptionItemsId());
                // 收费标准
                oldmanDepositEntity.setStandardPrice(oldmanDepositEntity.getStandardPrice());
                // 本月应收
                oldmanDepositEntity.setReceivableThisMonth(oldmanDepositEntity.getStandardPrice());
                // 费用类型
                oldmanDepositEntity.setFeeType(4);
                // 收费标记
                oldmanDepositEntity.setMark(checkinfeeEntity.getMark());
                // 缴费类型
                oldmanDepositEntity.setType("入院缴费");
                oldmanDepositEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanDepositEntity.setDateTo(time);

            }
            checkinfeeDetailService.saveOrUpdateBatch(deposit);

            // TODO 保存其他费用信息 3
            List<CheckinfeeDetailEntity> oldmanFixedcosts = dto.getFixedcosts();
            for (CheckinfeeDetailEntity oldmanFixedcostsEntity : oldmanFixedcosts) {
                // 收费id
                oldmanFixedcostsEntity.setCheckinfeeId(checkinfeeEntity.getId());
                // 老人id
                oldmanFixedcostsEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanFixedcostsEntity.setConsumptionItemsId(oldmanFixedcostsEntity.getConsumptionItemsId());
                // 收费标准
                oldmanFixedcostsEntity.setStandardPrice(oldmanFixedcostsEntity.getStandardPrice());
                // 本月应收
                oldmanFixedcostsEntity.setReceivableThisMonth(oldmanFixedcostsEntity.getStandardPrice());
                // 费用类型
                oldmanFixedcostsEntity.setFeeType(3);
                // 收费标记
                oldmanFixedcostsEntity.setMark(checkinfeeEntity.getMark());
                // 缴费类型
                oldmanFixedcostsEntity.setType("入院缴费");
                oldmanFixedcostsEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanFixedcostsEntity.setDateTo(time);

            }
            checkinfeeDetailService.saveOrUpdateBatch(oldmanFixedcosts);


            // TODO 1.新增护理费用收费记录
//        //1. 计算本月天数
//        LocalDateTime effectivetime = oldmanAttendance.getEffectivetime();
//        int day = effectivetime.getDayOfMonth();  //本月中第几天
//        System.out.println("本月中第几天" + day);
            // 新增一条入住收费 护理级别费用 记录
            CheckinfeeDetailEntity checkinfeeDetailEntity1 = new CheckinfeeDetailEntity();
            checkinfeeDetailEntity1.setOldmanId(oldmanAttendance.getOldmanId());
            checkinfeeDetailEntity1.setConsumptionItemsId(oldmanAttendance.getAttendanceId());
            checkinfeeDetailEntity1.setStandardPrice(oldmanAttendance.getAttendanceFee());
            checkinfeeDetailEntity1.setReceivableThisMonth(oldmanAttendance.getReceivableThisMonth());
            checkinfeeDetailEntity1.setFeeType(1);
            checkinfeeDetailEntity1.setMark(checkinfeeEntity.getMark());
            checkinfeeDetailEntity1.setStatus(0);
            checkinfeeDetailEntity1.setCheckinfeeId(checkinfeeEntity.getId());
            // 缴费类型
            checkinfeeDetailEntity1.setType("入院缴费");
            checkinfeeDetailEntity1.setDateStart(oldmanAttendance.getEffectivetime());
            checkinfeeDetailEntity1.setDateTo(time);

//        HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity1.getId()));

            //  TODO 5.新增定制护理收费记录
            // 计算定制护理费 获取费用 计算每天费用*天数
            BigDecimal privateCustomizationFee = oldmanAttendance.getPrivatecustomizationFee() == null ? BigDecimal.ZERO : oldmanAttendance.getPrivatecustomizationFee();
            BigDecimal privateCustomizationFeeDailyCost = privateCustomizationFee.divide(BigDecimal.valueOf(last), 6, BigDecimal.ROUND_HALF_UP);
            BigDecimal privateCustomizationFeeThisMonth = privateCustomizationFeeDailyCost.multiply(BigDecimal.valueOf(overday));

            CheckinfeeDetailEntity checkinfeeDetailEntity5 = new CheckinfeeDetailEntity();
            checkinfeeDetailEntity5.setOldmanId(oldmanAttendance.getOldmanId());
            checkinfeeDetailEntity5.setConsumptionItemsId(oldmanAttendance.getAttendanceId());
            checkinfeeDetailEntity5.setStandardPrice(oldmanAttendance.getPrivatecustomizationFee());
            checkinfeeDetailEntity5.setReceivableThisMonth(privateCustomizationFeeThisMonth);
            checkinfeeDetailEntity5.setFeeType(5);
            checkinfeeDetailEntity5.setMark(checkinfeeEntity.getMark());
            checkinfeeDetailEntity5.setStatus(0);
            checkinfeeDetailEntity5.setCheckinfeeId(checkinfeeEntity.getId());
            // 缴费类型
            checkinfeeDetailEntity5.setType("入院缴费");
            checkinfeeDetailEntity5.setDateStart(oldmanAttendance.getEffectivetime());
            checkinfeeDetailEntity5.setDateTo(time);
//        HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity5.getId()));

            // TODO 2.新增床位费用收费记录
            // 新增一条入住收费 床位费用 记录
            CheckinfeeDetailEntity checkinfeeDetailEntity2 = new CheckinfeeDetailEntity();
            checkinfeeDetailEntity2.setOldmanId(oldmanBed.getOldmanId());
            checkinfeeDetailEntity2.setConsumptionItemsId(oldmanBed.getBedId());
            checkinfeeDetailEntity2.setStandardPrice(oldmanBed.getFee());
            checkinfeeDetailEntity2.setReceivableThisMonth(oldmanBed.getReceivableThisMonth());
            checkinfeeDetailEntity2.setFeeType(2);
            checkinfeeDetailEntity2.setMark(checkinfeeEntity.getMark());
            checkinfeeDetailEntity2.setStatus(0);
            checkinfeeDetailEntity2.setCheckinfeeId(checkinfeeEntity.getId());
            // 缴费类型
            checkinfeeDetailEntity2.setType("入院缴费");
            checkinfeeDetailEntity2.setDateStart(oldmanBed.getEffectivetime());
            checkinfeeDetailEntity2.setDateTo(time);
//        HttpHeaders headers1 = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity2.getId()));

            // TODO 3.新增其他费用收费记录
//        List<CheckinfeeDetailEntity> checkinfeeDetailEntities = new ArrayList<>();
//        for (OldmanFixedcostsEntity oldmanFixedcostsEntity : oldmanFixedcosts) {
//            CheckinfeeDetailEntity checkinfeeDetailEntity3 = new CheckinfeeDetailEntity();
//            checkinfeeDetailEntity3.setFeeType(3);
//            checkinfeeDetailEntity3.setStandardPrice(oldmanFixedcostsEntity.getFee());
//            checkinfeeDetailEntity3.setOldmanId(oldmanFixedcostsEntity.getOldmanId());
//            checkinfeeDetailEntity3.setConsumptionItemsId(oldmanFixedcostsEntity.getItemId());
//            checkinfeeDetailEntity3.setReceivableThisMonth(oldmanFixedcostsEntity.getReceivableThisMonth());
//            checkinfeeDetailEntity3.setMark(checkinfeeEntity.getMark());
//            checkinfeeDetailEntity3.setStatus(0);
//            checkinfeeDetailEntity3.setCheckinfeeId(checkinfeeEntity.getId());
//            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity3.getId()));
//            checkinfeeDetailEntities.add(checkinfeeDetailEntity3);
//        }
//        // TODO 4.新增押金收费记录
//        List<CheckinfeeDetailEntity> checkinfeeDetailEntitys = new ArrayList<>();
//        for (OldmanDepositEntity oldmanDepositEntity : deposit) {
//            CheckinfeeDetailEntity checkinfeeDetailEntity4 = new CheckinfeeDetailEntity();
//            checkinfeeDetailEntity4.setFeeType(4);
//            checkinfeeDetailEntity4.setStandardPrice(oldmanDepositEntity.getFee());
//            checkinfeeDetailEntity4.setOldmanId(oldmanDepositEntity.getOldmanId());
//            checkinfeeDetailEntity4.setConsumptionItemsId(oldmanDepositEntity.getItemId());
//            checkinfeeDetailEntity4.setReceivableThisMonth(oldmanDepositEntity.getFee());
//            checkinfeeDetailEntity4.setMark(checkinfeeEntity.getMark());
//            checkinfeeDetailEntity4.setStatus(0);
//            checkinfeeDetailEntity4.setCheckinfeeId(checkinfeeEntity.getId());
////            checkinfeeEntity.setReceivableThisMonth(oldmanDepositEntity.getReceivableThisMonth());
////            HttpHeaders headers3 = new HttpHeaders();
//            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity4.getId()));
//            checkinfeeDetailEntitys.add(checkinfeeDetailEntity4);
//        }
            // TODO 6.新增餐饮收费记录
//        List<CheckinfeeDetailEntity> checkinfeeDetailEntitysdf = new ArrayList<>();
//        for (OldmanDiningfeeEntity oldmanDiningfeeEntity : diningfee) {
//            CheckinfeeDetailEntity checkinfeeDetailEntity6 = new CheckinfeeDetailEntity();
//            checkinfeeDetailEntity6.setFeeType(6);
//            checkinfeeDetailEntity6.setStandardPrice(oldmanDiningfeeEntity.getFee());
//            checkinfeeDetailEntity6.setOldmanId(oldmanDiningfeeEntity.getOldmanId());
//            checkinfeeDetailEntity6.setConsumptionItemsId(oldmanDiningfeeEntity.getItemId());
//            checkinfeeDetailEntity6.setReceivableThisMonth(oldmanDiningfeeEntity.getFee());
//            checkinfeeDetailEntity6.setMark(checkinfeeEntity.getMark());
//            checkinfeeDetailEntity6.setStatus(0);
//            checkinfeeDetailEntity6.setCheckinfeeId(checkinfeeEntity.getId());
//            checkinfeeDetailEntity6.setReceivableThisMonth(oldmanDiningfeeEntity.getReceivableThisMonth());
//            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity6.getId()));
//            checkinfeeDetailEntitysdf.add(checkinfeeDetailEntity6);
//        }
            // TODO 7.新增水电收费记录
//        List<CheckinfeeDetailEntity> checkinfeeDetailEntitysub = new ArrayList<>();
//        for (OldmanUtilitybillEntity oldmanUtilitybillEntity : utilitybill) {
//            CheckinfeeDetailEntity checkinfeeDetailEntity7 = new CheckinfeeDetailEntity();
//            checkinfeeDetailEntity7.setFeeType(7);
//            checkinfeeDetailEntity7.setStandardPrice(oldmanUtilitybillEntity.getFee());
//            checkinfeeDetailEntity7.setOldmanId(oldmanUtilitybillEntity.getOldmanId());
//            checkinfeeDetailEntity7.setConsumptionItemsId(oldmanUtilitybillEntity.getItemId());
//            checkinfeeDetailEntity7.setReceivableThisMonth(oldmanUtilitybillEntity.getFee());
//            checkinfeeDetailEntity7.setMark(checkinfeeEntity.getMark());
//            checkinfeeDetailEntity7.setStatus(0);
//            checkinfeeDetailEntity7.setCheckinfeeId(checkinfeeEntity.getId());
//            checkinfeeDetailEntity7.setReceivableThisMonth(oldmanUtilitybillEntity.getReceivableThisMonth());
//            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity7.getId()));
//            checkinfeeDetailEntitysub.add(checkinfeeDetailEntity7);
//        }

            /**
             * 保存入院收费记录
             */
            List<CheckinfeeDetailEntity> checkinfeeDetailEntityList = new ArrayList<>();
            checkinfeeDetailEntityList.add(checkinfeeDetailEntity1); // 护理级别费用
            checkinfeeDetailEntityList.add(checkinfeeDetailEntity2); // 床位费用
            checkinfeeDetailEntityList.add(checkinfeeDetailEntity5); // 定制护理费用
            checkinfeeDetailService.saveOrUpdateBatch(checkinfeeDetailEntityList);
//        checkinfeeDetailService.saveOrUpdateBatch(checkinfeeDetailEntities); // 其他费用
//        checkinfeeDetailService.saveOrUpdateBatch(checkinfeeDetailEntitys); // 押金
//        checkinfeeDetailService.saveOrUpdateBatch(checkinfeeDetailEntitysdf); // 餐饮费
//        checkinfeeDetailService.saveOrUpdateBatch(checkinfeeDetailEntitysub); // 水电费

            // 如果缴费记录为 未缴费 类别为入院缴费 则初始化入院缴费记录以及明细
        } else if (checkinfee.getStatus() == 0 && checkinfee.getCategory() == 1) {
            System.out.println("checkinfee不为空");

            // 更新入院缴费记录
            Calendar ca = Calendar.getInstance();
            ca.setTime(oldmanAttendance.getEffectivetime());
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date time = ca.getTime();
            System.out.println("time=修改时===" + time);
//            String day2= format.format(ca.getTime());
            checkinfee.setDateTo(time);
            checkinfee.setDateStart(oldmanAttendance.getEffectivetime());
            checkinfee.setBedId(oldmanBed.getBedId());
            checkinfee.setAttendanceId(oldmanAttendance.getAttendanceId());
            checkinfeeService.lambdaUpdate()
                    .set(CheckinfeeEntity::getBedId, checkinfee.getBedId())
                    .set(CheckinfeeEntity::getAttendanceId, checkinfee.getAttendanceId())
                    .set(CheckinfeeEntity::getDateStart, checkinfee.getDateStart())
                    .set(CheckinfeeEntity::getDateTo, checkinfee.getDateTo())
                    .eq(CheckinfeeEntity::getId, checkinfee.getId())
                    .update();
            // 更新缴费明细
            // 1.删除原来的明细
            List<CheckinfeeDetailEntity> checkinfeeDetailList = checkinfeeDetailService.getCheckinfeeDetailByCheckinfeeId(checkinfee.getId());
            List<String> checkinfeeDetailIds = checkinfeeDetailList.stream().map(CheckinfeeDetailEntity::getId).collect(Collectors.toList());
            checkinfeeDetailService.removeByIds(checkinfeeDetailIds);


            // 2.新增缴费明细
            // 1.护理级别信息
            CheckinfeeDetailEntity checkinfeeDetailEntity1 = new CheckinfeeDetailEntity();
            checkinfeeDetailEntity1.setOldmanId(oldmanAttendance.getOldmanId());
            checkinfeeDetailEntity1.setConsumptionItemsId(oldmanAttendance.getAttendanceId());
            checkinfeeDetailEntity1.setStandardPrice(oldmanAttendance.getAttendanceFee());
            checkinfeeDetailEntity1.setReceivableThisMonth(oldmanAttendance.getReceivableThisMonth());
            checkinfeeDetailEntity1.setFeeType(1);
            checkinfeeDetailEntity1.setMark(checkinfee.getMark());
            checkinfeeDetailEntity1.setStatus(0);
            checkinfeeDetailEntity1.setCheckinfeeId(checkinfee.getId());
            // 缴费类型
            checkinfeeDetailEntity1.setType("入院缴费");
            checkinfeeDetailEntity1.setDateStart(oldmanAttendance.getEffectivetime());
            checkinfeeDetailEntity1.setDateTo(time);
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity1.getId()));

            //  5.新增定制护理收费记录
            // 计算定制护理费 获取费用 计算每天费用*天数
            BigDecimal privateCustomizationFee = oldmanAttendance.getPrivatecustomizationFee() == null ? BigDecimal.ZERO : oldmanAttendance.getPrivatecustomizationFee();
            BigDecimal privateCustomizationFeeDailyCost = privateCustomizationFee.divide(BigDecimal.valueOf(last), 6, BigDecimal.ROUND_HALF_UP);
            BigDecimal privateCustomizationFeeThisMonth = privateCustomizationFeeDailyCost.multiply(BigDecimal.valueOf(overday));

            CheckinfeeDetailEntity checkinfeeDetailEntity5 = new CheckinfeeDetailEntity();
            checkinfeeDetailEntity5.setOldmanId(oldmanAttendance.getOldmanId());
            checkinfeeDetailEntity5.setConsumptionItemsId(oldmanAttendance.getAttendanceId());
            checkinfeeDetailEntity5.setStandardPrice(oldmanAttendance.getPrivatecustomizationFee());
            checkinfeeDetailEntity5.setReceivableThisMonth(privateCustomizationFeeThisMonth);
            checkinfeeDetailEntity5.setFeeType(5);
            checkinfeeDetailEntity5.setMark(checkinfee.getMark());
            checkinfeeDetailEntity5.setStatus(0);
            checkinfeeDetailEntity5.setCheckinfeeId(checkinfee.getId());
            checkinfeeDetailEntity5.setType("入院缴费");
            checkinfeeDetailEntity5.setDateStart(oldmanAttendance.getEffectivetime());
            checkinfeeDetailEntity5.setDateTo(time);
//        HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity5.getId()));

            // 2.新增床位费用收费记录
            // 新增一条入住收费 床位费用 记录
            CheckinfeeDetailEntity checkinfeeDetailEntity2 = new CheckinfeeDetailEntity();
            checkinfeeDetailEntity2.setOldmanId(oldmanBed.getOldmanId());
            checkinfeeDetailEntity2.setConsumptionItemsId(oldmanBed.getBedId());
            checkinfeeDetailEntity2.setStandardPrice(oldmanBed.getFee());
            checkinfeeDetailEntity2.setReceivableThisMonth(oldmanBed.getReceivableThisMonth());
            checkinfeeDetailEntity2.setFeeType(2);
            checkinfeeDetailEntity2.setMark(checkinfee.getMark());
            checkinfeeDetailEntity2.setStatus(0);
            checkinfeeDetailEntity2.setCheckinfeeId(checkinfee.getId());
            checkinfeeDetailEntity2.setType("入院缴费");
            checkinfeeDetailEntity2.setDateStart(oldmanBed.getEffectivetime());
            checkinfeeDetailEntity2.setDateTo(time);

//        HttpHeaders headers1 = new HttpHeaders();
            headers.add(HttpHeaders.LOCATION, String.valueOf(checkinfeeDetailEntity2.getId()));

            // 保存缴费明细记录
            List<CheckinfeeDetailEntity> checkinfeeDetailEntityList = new ArrayList<>();
            checkinfeeDetailEntityList.add(checkinfeeDetailEntity1); // 护理级别费用
            checkinfeeDetailEntityList.add(checkinfeeDetailEntity2); // 床位费用
            checkinfeeDetailEntityList.add(checkinfeeDetailEntity5); // 定制护理费用
            checkinfeeDetailService.saveOrUpdateBatch(checkinfeeDetailEntityList);

            // 6 保存餐饮费用信息
            // 获取新的餐饮费用
            List<CheckinfeeDetailEntity> diningfee = dto.getDiningfee();
            System.out.println("diningfee00000" + diningfee);

            for (CheckinfeeDetailEntity oldmanDiningfeeEntity : diningfee) {
                System.out.println("oldmanDiningfeeEntity:::" + oldmanDiningfeeEntity);
                // 收费id
                oldmanDiningfeeEntity.setCheckinfeeId(checkinfee.getId());
                // 老人id
                oldmanDiningfeeEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanDiningfeeEntity.setConsumptionItemsId(oldmanDiningfeeEntity.getConsumptionItemsId());
                // 收费标准
                oldmanDiningfeeEntity.setStandardPrice(oldmanDiningfeeEntity.getStandardPrice());
                // 费用类型
                oldmanDiningfeeEntity.setFeeType(6);
                // 收费标记
                oldmanDiningfeeEntity.setMark(checkinfee.getMark());
                oldmanDiningfeeEntity.setType("入院缴费");
                oldmanDiningfeeEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanDiningfeeEntity.setDateTo(time);


                // 计算餐饮费
                BigDecimal fee1 = oldmanDiningfeeEntity.getStandardPrice() == null ? BigDecimal.ZERO : oldmanDiningfeeEntity.getStandardPrice();
                // 餐饮费每日费用
                BigDecimal DailyCost = fee1.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
                // 每天费用 * 本月剩余天数 = 本月应收费用
                BigDecimal costThisMonth = DailyCost.multiply(BigDecimal.valueOf(overday1));
                oldmanDiningfeeEntity.setReceivableThisMonth(costThisMonth);
                System.out.println("餐饮费" + oldmanDiningfeeEntity.getReceivableThisMonth());
            }
            checkinfeeDetailService.saveOrUpdateBatch(diningfee);


            // 7 保存水电费用信息
            List<CheckinfeeDetailEntity> utilitybill = dto.getUtilitybill();
            for (CheckinfeeDetailEntity oldmanUtilitybillEntity : utilitybill) {
                System.out.println("oldmanUtilitybillEntity:::" + oldmanUtilitybillEntity);

                // 收费id
                oldmanUtilitybillEntity.setCheckinfeeId(checkinfee.getId());
                // 老人id
                oldmanUtilitybillEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanUtilitybillEntity.setConsumptionItemsId(oldmanUtilitybillEntity.getConsumptionItemsId());
                // 收费标准
                oldmanUtilitybillEntity.setStandardPrice(oldmanUtilitybillEntity.getStandardPrice());
                // 费用类型
                oldmanUtilitybillEntity.setFeeType(7);
                // 收费标记
                oldmanUtilitybillEntity.setMark(checkinfee.getMark());
                oldmanUtilitybillEntity.setType("入院缴费");
                oldmanUtilitybillEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanUtilitybillEntity.setDateTo(time);


                // 计算水电费
                BigDecimal fee1 = oldmanUtilitybillEntity.getStandardPrice() == null ? BigDecimal.ZERO : oldmanUtilitybillEntity.getStandardPrice();
                // 水电费每日费用
                BigDecimal DailyCost = fee1.divide(BigDecimal.valueOf(last1), 6, BigDecimal.ROUND_HALF_UP);
                System.out.println("水电费 DailyCost" + DailyCost);
                // 每天费用 * 本月剩余天数 = 本月应收费用
                BigDecimal costThisMonth = DailyCost.multiply(BigDecimal.valueOf(overday1));

                oldmanUtilitybillEntity.setReceivableThisMonth(costThisMonth);
                System.out.println("水电费" + oldmanUtilitybillEntity.getReceivableThisMonth());
            }
            checkinfeeDetailService.saveOrUpdateBatch(utilitybill);

            // 4 保存押金信息
            List<CheckinfeeDetailEntity> deposit = dto.getDeposit();
//        OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(oldmanAttendance.getOldmanId());
            for (CheckinfeeDetailEntity oldmanDepositEntity : deposit) {
                System.out.println("oldmanDepositEntity:::" + oldmanDepositEntity);

//            oldmanDepositEntity.setCertificate(oldmanInfoEntity.getCertificate());
//            oldmanDepositEntity.setStatus(oldmanInfoEntity.getStatus());
                // 收费id
                oldmanDepositEntity.setCheckinfeeId(checkinfee.getId());
                // 老人id
                oldmanDepositEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanDepositEntity.setConsumptionItemsId(oldmanDepositEntity.getConsumptionItemsId());
                // 收费标准
                oldmanDepositEntity.setStandardPrice(oldmanDepositEntity.getStandardPrice());
                // 本月应收
                oldmanDepositEntity.setReceivableThisMonth(oldmanDepositEntity.getStandardPrice());
                // 费用类型
                oldmanDepositEntity.setFeeType(4);
                // 收费标记
                oldmanDepositEntity.setMark(checkinfee.getMark());
                oldmanDepositEntity.setType("入院缴费");
                oldmanDepositEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanDepositEntity.setDateTo(time);

            }
            checkinfeeDetailService.saveOrUpdateBatch(deposit);

            // 3 保存其他费用信息
            List<CheckinfeeDetailEntity> oldmanFixedcosts = dto.getFixedcosts();
            // 计算水电费
            for (CheckinfeeDetailEntity oldmanFixedcostsEntity : oldmanFixedcosts) {
                System.out.println("oldmanFixedcostsEntity:::" + oldmanFixedcostsEntity);

                // 收费id
                oldmanFixedcostsEntity.setCheckinfeeId(checkinfee.getId());
                // 老人id
                oldmanFixedcostsEntity.setOldmanId(oldmanAttendance.getOldmanId());
                // 收费项目
                oldmanFixedcostsEntity.setConsumptionItemsId(oldmanFixedcostsEntity.getConsumptionItemsId());
                // 收费标准
                oldmanFixedcostsEntity.setStandardPrice(oldmanFixedcostsEntity.getStandardPrice());
                // 本月应收
                oldmanFixedcostsEntity.setReceivableThisMonth(oldmanFixedcostsEntity.getStandardPrice());
                // 费用类型
                oldmanFixedcostsEntity.setFeeType(3);
                // 收费标记
                oldmanFixedcostsEntity.setMark(checkinfee.getMark());
                oldmanFixedcostsEntity.setType("入院缴费");
                oldmanFixedcostsEntity.setDateStart(oldmanBed.getEffectivetime());
                oldmanFixedcostsEntity.setDateTo(time);

            }
            checkinfeeDetailService.saveOrUpdateBatch(oldmanFixedcosts);

//            List<CheckinfeeDetailEntity> monthlyfees1 = dto.getMonthlyfees();
//            monthlyfees1.forEach(monthlyfee -> {
//                monthlyfee.setCheckinfeeId(checkinfee.getId());
//                monthlyfee.setMark(checkinfee.getMark());
//            });
//            checkinfeeDetailService.saveOrUpdateBatch(monthlyfees1);
        }

    }


    /**
     * 判断老人证件信息是否重复
     *
     * @param oldman 老人信息
     */
    private void checkOldManCertificateAlready(OldmanInfoEntity oldman) {
        if (oldman.getId() != null) {
            // 这是一个转入住的老人信息
            return;
        }
        Integer oldmanNum = oldmanInfoService.lambdaQuery()
                .eq(OldmanInfoEntity::getCertificate, oldman.getCertificate())
                .eq(OldmanInfoEntity::getCertificateType, oldman.getCertificateType())
                .count();
        if (oldmanNum > 0) {
            throw new RuntimeException("已经存在该老人的证件信息，请勿重复添加入住");
        }
    }

    /**
     * 保存老人家属信息
     *
     * @param familys 家属列表
     */
    private void saveFamilys(OldmanInfoEntity oldman, List<OldmanFamilydependentEntity> familys) {
        String oldmanId = oldman.getId();
        familys.forEach(entity -> entity.setOldmanId(oldmanId));
        oldmanFamilydependentService.saveOrUpdateBatch(familys);
    }

    /**
     * 保存老人健康信息
     *
     * @param oldman  老人信息
     * @param healths 老人健康记录列表
     */
    private void saveHealths(OldmanInfoEntity oldman, List<OldmanHealthInformationEntity> healths) {
        String oldmanId = oldman.getId();
        healths.forEach(entity -> entity.setOldmanId(oldmanId));
        oldmanHealthInformationService.saveOrUpdateBatch(healths);
    }

    /**
     * 检查床位信息
     *
     * @param bedEntity 床位信息
     */
    private void checkBedInfo(BedEntity bedEntity) {
        String bedEntityId = bedEntity.getId();
        if (bedEntityId == null) {
            throw new RuntimeException("床位信息错误");
        }
        BedEntity entity = bedService.getById(bedEntityId);
        if (entity == null) {
            throw new RuntimeException("找不到床位信息");
        }
        if (entity.getOldmanId() != null) {
            throw new RuntimeException("该床位已有人入住（或有人预约）");
        }
    }

    /**
     * 更改床位信息，使床位关联老人信息
     *
     * @param oldman    老人信息
     * @param bedEntity 床位信息
     */
    private void updateBedInfo(OldmanInfoEntity oldman, BedEntity bedEntity) {
        String oldmanId = oldman.getId();
        bedService.lambdaUpdate()
                .set(true, BedEntity::getOldmanId, oldmanId)
                .eq(BedEntity::getId, bedEntity.getId())
                .update();
    }

    /**
     * 保存入住记录
     *
     * @param dto 包装信息
     */
    private void saveCheckInRecord(CheckInDTO dto) {
        CheckInRecordEntity checkInRecord = dto.getCheckInRecord();
        checkInRecord.setId(null);
        checkInRecord.setOldmanId(dto.getOldman().getId());

        checkInRecordService.save(checkInRecord);
    }

    /**
     * 生成费用订单信息
     *
     * @param dto 包装对象
     */
    private void generateExpenseRecords(CheckInDTO dto) {
        CardNumberEntity cardNumberEntity = cardNumberService.getByPersonId(dto.getOldman().getId());
        String membercard = cardNumberEntity.getMemberCard();
        // 生成房间价格账单
        BedEntity bedEntity = bedService.getById(dto.getBed().getId());
        RoomTypeEntity roomTypeEntity = roomTypeService.getByRoomId(bedEntity.getBedRoomId());
        cardExpenseRecordService.consumptionByMemberNumber(membercard,
                roomTypeEntity.getBedPrice(), CardExpenseRecordType.accommodation,
                dto.getOldman().getOldmanName() + "入住住宿费");
        cardExpenseRecordService.consumptionByMemberNumber(membercard,
                roomTypeEntity.getEarnestMoney(), CardExpenseRecordType.deposit,
                dto.getOldman().getOldmanName() + "入住押金");
    }
}
